﻿using SearchForWorkitemsChanges.ExternalActions.ExportXmlComponents;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace SearchForWorkitemsChanges.ExternalActions
{
    /// <summary>
    /// This class is a implementing class of <see cref="IExternalAction"/> for the Xml export plugin
    /// </summary>
    internal class ExportXml : IExternalAction
    {
        /// <summary>
        /// Name displayed on the button
        /// </summary>
        public string DisplayName
        {
            get { return "Export Xml"; }
        }

        /// <summary>
        /// ToolTip displayed on the button
        /// </summary>
        public string TooltipDescription
        {
            get { return "Export the workitems in a Xml file"; }
        }

        /// <summary>
        /// Execute called on button click
        /// </summary>
        /// <param name="workitems">The search result</param>
        public void Execute(IEnumerable<Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem> workitems)
        {
            var dstFile = LocateDestinationFile();

            if (dstFile == null)
                return;

            if (dstFile.Exists)
                dstFile.Delete();

            var serializer = new XmlSerializer(typeof(WorkItemsContainer));

            using (var str = dstFile.OpenWrite())
            {
                serializer.Serialize(str, Convert(workitems));
                str.Flush();
                str.Close();
            }

            MessageBox.Show("Export done !");
        }

        private static WorkItemsContainer Convert(IEnumerable<WorkItem> source)
        {
            var returnedValue = new WorkItemsContainer() { WorkItems = new List<SerializedFacadeWorkItem>() };

            foreach (var wi in source)
                returnedValue.WorkItems.Add(new SerializedFacadeWorkItem(wi));

            return returnedValue;
        }

        private static FileInfo LocateDestinationFile()
        {
            FileInfo result = null;
            using (var saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.CheckPathExists = true;
                saveFileDialog.DefaultExt = "xml";
                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                saveFileDialog.Filter = "Xml files (*.xml)|*.xml";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {

                    result = new FileInfo(saveFileDialog.FileName.EndsWith(".xml") ? saveFileDialog.FileName : saveFileDialog.FileName + ".xml");
                }
            }

            return result;
        }
    }
}
